package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.wapi.model.WxUser;
import cn.topevery.garden.wapi.utils.WeChatCommon;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "wx相关")
@RestController
@RequestMapping(value = "/rs/wx")
public class WxController {

    private static final String APPID = "wx2e8172661ea123f6";
    private static final String APPSECRET = "e5af9b3fd640a461a11796bcaed676c6";

    @RequestMapping(value = "/getOpenId", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult<?> getOpenId(@RequestBody WxUser param) {

        Map<String, Object> ret = new HashMap<>();
        try {
            JSONObject json;
            WxUser wxUser = new WxUser();
                WeChatCommon weChatCommon = new WeChatCommon();
                json = weChatCommon.getOpenId(APPID, APPSECRET, param.getCode());
                if(!json.containsKey("errcode")) {
                    wxUser.setOpenId(json.getString("openid"));
                    wxUser.setSessionKey(json.getString("session_key"));
                }
            if(StringUtils.isBlank(wxUser.getOpenId())) {
                return JsonResult.error("error");
            }

            ret.put("openid", wxUser.getOpenId());
            ret.put("session_key", wxUser.getSessionKey());
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error("error");
        }
        return JsonResult.ok(ret);
    }
}
